package com.example.servlet;


import com.example.Service.UserService;
import com.example.pojo.User;
import com.google.gson.Gson;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.*;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@MultipartConfig
@WebServlet(name = "FileUploadServlet", value = "/FileUploadServlet")
public class FileUploadServlet extends HttpServlet {
    private String message;

    public void init() {
        message = "Hello World!";
    }

    public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.setContentType("text/html");

        // Hello
        PrintWriter out = response.getWriter();
        out.println("<html><body>");
        out.println("<h1>" + message + "</h1>");
        out.println("</body></html>");
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
     //1获取用户提交的数据 get reg.getParameter();post 文本：BufferedReader;文件 Part
        Part part = req.getPart("file");
        System.out.println(part.getSubmittedFileName());
    //2 1)存储在服务器中的位置2）重新命名
        File path=new File(req.getServletContext().getRealPath("upload/"));
//      File path=new File("d:/upload/");//创建在D盘
        //如果文件夹不存在就创建
        if (!path.exists()){
            path.mkdirs();
        }
        //重新命名
        String originalName =part.getSubmittedFileName();
        String newName =UUID.randomUUID().toString()+ originalName.substring(originalName.lastIndexOf("."));
        File uploadFile =new  File(path,newName);
        part.write(uploadFile.getAbsolutePath());
        //3响应
        Map<String,Object> map =new HashMap<>();
        map.put("code",200);
        map.put("msg","上传成功");
        map.put("filename","upload/"+newName);
        Gson gson =new Gson();
        resp.getWriter().append(gson.toJson(map));

    }

    public void destroy() {
    }
}
